<template>
  <div class="flex_cm container" style="height: 100%">
    <search
      :form_data="header_list"
      @changeIsShow="
        (e) => {
          header_list[e].isShow = !header_list[e].isShow
          header_list[e].value =
            header_list[e].type == 'input_number' ? ['', ''] : ''
        }
      "
      @search="search_key"
      @reset="
        header_list.forEach((item) => {
          item.value = ''
        }),
          search_key()
      "
    ></search>
    <div class="p_0_10 bg_fff flex1">
      <div class="flex_js p_10_0">
        <div>标准件</div>
        <div class="flex">
          <div>当前服务企业</div>
          <el-select
            class="m_0_10"
            v-model="serviceEnterpriseId"
            @change="search_key()"
          >
            <el-option
              v-for="item in serviceEnterpriseList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
          <el-button type="primary" @click="show_box = true">新增</el-button>
          <setTable
            :data="header_list"
            :height_size="height_size"
            @changeShowTable="
              (e) => {
                header_list[e].showTable = !header_list[e].showTable
              }
            "
            @resetTableSet="
              () => {
                header_list.forEach((item) => {
                  item.showTable = true
                })
              }
            "
            @changeHeightSize="
              (e) => {
                height_size = e
              }
            "
          ></setTable>
        </div>
      </div>
      <el-table
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
        :default-sort="{ prop: 'name', order: 'descending' }"
        :row-style="{
          height:
            height_size == 1 ? '58px' : height_size == 2 ? '48px' : '38px',
        }"
        row-key="id"
        :cell-style="{
          padding: height_size == 3 ? '0' : '',
        }"
      >
        <el-table-column
          type="index"
          label="序号"
          width="80px"
        ></el-table-column>
        <el-table-column
          label="名称"
          prop="code"
          key="项目名称"
          sortable
          v-if="header_list[0].showTable"
        ></el-table-column>
        <!-- <el-table-column label="状态" key="状态" sortable v-if="header_list[1].showTable">
          <template #default="scope">
            <div v-if="!scope.row.isDelete">启用</div>
            <div v-else>禁用</div>
          </template>
        </el-table-column> -->
        <el-table-column label="操作">
          <template #default="scope">
            <el-button @click="edit_list({ item: scope.row, type: 1 })"
              >编辑</el-button
            >
            <el-button @click="edit_list({ item: scope.row, type: 2 })">
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-drawer
      v-model="show_box"
      direction="rtl"
      size="50%"
      destroy-on-close
      @close="resetForm(addPartsform)"
      :close-on-click-modal="false"
    >
      <template #title>
        <h4 v-if="add_form_data.id == ''">新增标准件</h4>
        <h4 v-else>编辑标准件</h4>
      </template>
      <template #default>
        <el-form
          :model="add_form_data"
          ref="addPartsform"
          :rules="rules"
          label-width="120"
        >
          <el-form-item label="名称" prop="code">
            <el-input v-model="add_form_data.code"></el-input>
          </el-form-item>
          <el-form-item label="父级">
            <el-cascader
              v-model="add_form_data.parentId"
              :options="add_select_praentId_list"
              :props="props1"
              clearable
            />
          </el-form-item>
          <el-form-item label="排序" v-if="add_form_data.id != ''">
            <el-input v-model="add_form_data.sort"></el-input>
          </el-form-item>
          <div class="m_top10 tr">
            <el-button @click="resetForm(addPartsform)">取消</el-button>
            <el-button
              :loading="btn_loading"
              type="primary"
              @click="submit(addPartsform)"
              >确定</el-button
            >
          </div>
        </el-form>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { check_role, handle_search_key } from '@/utils/check_role' // 权限校验
import search from '@/view/components/search.vue'
import setTable from '@/view/components/setTable.vue'
import { onMounted, ref, onUnmounted, computed } from 'vue'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
const addPartsform = ref<FormInstance>()
const rules = ref({
  // 表单验证规则
  code: [{ required: true, message: '请输入名称', trigger: 'blur' }],
})
const props1 = {
  checkStrictly: true,
}
const list = ref([])
const max_height = ref()
const loading = ref(false)
const show_box = ref(false)
const height_size = ref(1)
const header_list = ref<any>([
  {
    label: '名称',
    value: '',
    showTable: true,
    type: 'input',
    isShow: true,
    options: [],
  },
  //   {
  //     label: "状态",
  //     value: "",
  //     showTable: true,
  //     type: "select",
  //     isShow: true,
  //     options: [
  //       { label: "启用", value: true },
  //       { label: "禁用", value: false },
  //     ],
  //   },
])
const add_form_data = ref({
  id: '',
  code: '',
  parentId: '',
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value
  }),
  sort: '',
})
const page_data = ref({
  code: '',
  //   isDelele: "",
  serviceEnterpriseId: computed(() => {
    return serviceEnterpriseId.value
  }),
})
onMounted(() => {
  max_height.value = window.innerHeight - 280 // 带分页的 table 高度
  EventBus.on('refresh', () => {
    get_list()
    ElMessage.success('刷新成功！')
  })
  get_serviceEnterpriseList()
})
onUnmounted(() => {
  EventBus.off('refresh')
})
const edit_list = (e) => {
  if (e.type == 1) {
    select_list_disabled(e.item.id, list.value)
    add_form_data.value = {
      id: e.item.id,
      code: e.item.code,
      parentId: e.item.parentId,
      serviceEnterpriseId: e.item.serviceEnterpriseId,
      sort: e.item.sort,
    }
    show_box.value = true
  } else {
    ElMessageBox.confirm('确定删除该记录？', '', {
      cancelButtonText: '取消',
      confirmButtonText: '确定',
      closeOnClickModal: false,
      type: 'warning',
    })
      .then(() => {
        axios
          .request({
            url: serviceApi.standardParts + '/' + e.item.id,
            method: 'delete',
          })
          .then(() => {
            ElMessage.success('操作成功！')
            setTimeout(() => {
              get_list()
            }, 1000)
          })
          .catch((err) => {
            ElMessage.error(err)
          })
      })
      .catch(() => {})
  }
}
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      if (btn_loading.value) return
      btn_loading.value = true
      add_form_data.value.parentId = Array.isArray(add_form_data.value.parentId)
        ? add_form_data.value.parentId.at(-1)
        : add_form_data.value.parentId
      console.log(add_form_data.value)
      //   return;
      axios
        .request({
          url:
            serviceApi.standardParts +
            (add_form_data.value.id == '' ? '' : '/' + add_form_data.value.id),
          method: 'post',
          data: add_form_data.value,
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
            btn_loading.value = false
            show_box.value = false
          }, 1000)
        })
        .catch((err) => {
          ElMessage.error(err)
          btn_loading.value = false
        })
    }
  })
}
const btn_loading = ref(false)
const add_select_praentId_list = ref([])
const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.standardParts + '/list',
      method: 'post',
      data: handle_search_key(page_data.value),
    })
    .then((res) => {
      list.value = arrToTree(res.data)
      add_select_praentId_list.value =
        page_data.value.code == ''
          ? JSON.parse(JSON.stringify(list.value))
          : add_select_praentId_list.value
      console.log(list.value, add_select_praentId_list.value)
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
const serviceEnterpriseId = ref()
const serviceEnterpriseList = ref([])
const get_serviceEnterpriseList = () => {
  axios
    .request({ url: serviceApi.serviceEnterpriseList, method: 'post' })
    .then((res) => {
      console.log(res)
      serviceEnterpriseList.value = res.data === null ? [] : res.data
      serviceEnterpriseId.value = res.data === null ? '' : res.data[0].id
      get_list()
    })
}
const search_key = () => {
  page_data.value = {
    code: header_list.value[0].value,
    // isDelele: header_list.value[1].value,
    serviceEnterpriseId: serviceEnterpriseId.value,
  }
  get_list()
}
// 级联选择 禁用自身
const select_list_disabled = (e, arr, flag?) => {
  arr.forEach((i) => {
    if (i.id == e) {
      i.disabled = true
      if (i.children) {
        // 下级不可选
        select_list_disabled(e, i.children, true)
      }
    } else {
      if (flag) {
        i.disabled = true
        if (i.children) {
          // 下级不可选
          select_list_disabled(e, i.children, true)
        }
      } else {
        i.disabled = false
        if (i.children) {
          select_list_disabled(e, i.children)
        }
      }
    }
  })
}
const arrToTree = (list) => {
  var map = {}
  var result = []
  list.forEach((item) => {
    map[item.id] = item
  })
  list.forEach((item) => {
    item.value = item.id
    item.label = item.code
    item.disabled = item.level == 3
    let parent = map[item.parentId]
    if (parent) {
      if (!parent.children) {
        parent.children = []
      }
      parent.children.push(item)
      parent.children.sort(function (a, b) {
        return a.sort - b.sort
      })
    } else if (!parent) {
      result.push(item)
    }
  })
  return result
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    id: '',
    code: '',
    parentId: '',
    serviceEnterpriseId: add_form_data.value.serviceEnterpriseId,
    sort: '',
  }
  show_box.value = false
}
</script>

<style lang="scss" scoped>
.top_item {
  border: 1px solid #ccc;
  cursor: pointer;
  padding: 5px;
  border-radius: 5px;
  display: flex;
  align-items: center;
  &:hover {
    color: #3580eb;
    border-color: #3580eb;
  }
}
.line {
  background-color: #333;
  width: 1px;
  height: 16px;
  margin: 0 10px;
}
</style>
